// ignore_for_file: use_build_context_synchronously

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/mine_charge_coin_page.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_page.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/format_util.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/routers/jump_router.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/loading/loading_alert_widget.dart';
import 'package:tiktokadult/tools_base/net/base_resp_bean.dart';

import '../../hj_model/ticket_list_model.dart';
import '../../hj_model/user/wallet_model_entity.dart';
import '../../hj_model/video_model.dart';
import '../../hj_utils/global.dart';
import '../../tools_base/global_store/store.dart';
import '../../tools_base/net/api_exception.dart';

///购买视频对话框
class VideoBuyAlert extends StatefulWidget {
  static Future show(VideoModel? model, {String? desc, bool? presale}) {
    return Get.bottomSheet(VideoBuyAlert(model, desc: desc, presale: presale));
  }

  final VideoModel? videoModel;
  final String? desc;
  final bool? presale; //是否是预售期间vip弹窗
  const VideoBuyAlert(this.videoModel, {super.key, this.desc, this.presale});

  @override
  State<StatefulWidget> createState() {
    return _VideoBuyAlertState();
  }
}

class _VideoBuyAlertState extends State<VideoBuyAlert> {
  bool isBuying = false;

  bool get isVip => globalStore.isVIP();

  bool get isHasCoupon {
    return discountArr.isNotEmpty;
  }

  TicketModel? selectEntity;
  List<TicketModel> discountArr = [];

  WalletModelEntity? get wallet => globalStore.wallet;

  int get mediaCoin => widget.videoModel?.realCoins ?? 0;

  @override
  void initState() {
    super.initState();
    globalStore.refreshWallet().then((value) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  ///购买作品
  _buyProduct(bool isMoneyEnough) async {
    if (isMoneyEnough == false) {
      showToast("余额不足");
      await jumpToWalletPage(tabPosition: 1);
      isMoneyEnough = true;
      setState(() {});
      return;
    }
    if (isBuying) return;
    isBuying = true;
    setState(() {});
    try {
      String? productID = widget.videoModel?.id;
      LoadingAlertWidget.show();
      BaseRespBean data = await MineService.postBuyVideo(
        productID,
        1,
        goldVideoCouponNum: selectEntity?.goodsValue,
      );
      LoadingAlertWidget.cancel();
      if (data.isSuccess) {
        widget.videoModel?.vidStatus?.hasPaid = true;
        globalStore.updateUserInfo();
        Navigator.pop(context, true);
      } else {
        if (data.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          showToast("网络异常, 支付失败");
        }
      }
    } on DioException catch (e) {
      LoadingAlertWidget.cancel();
      var error = e.error;
      if (error is ApiException) {
        if (error.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          showToast(error.message);
        }
      } else {
        showToast(e.toString());
      }

      debugLog('productBuy', e.toString());
    } catch (e) {
      LoadingAlertWidget.cancel();
      debugLog('postBuyVideo', e.toString());
    }
    isBuying = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.bottomCenter,
      child: Material(
        color: Colors.transparent,
        child: Consumer<GlobalStore>(
          builder: (context, _, child) {
            bool enough = (_.wallet?.amount ?? 0) >= mediaCoin;

            if (widget.presale == true) {
              return _buildPresaleContent(_, enough);
            } else {
              return _buildNormal(enough);
            }
          },
        ),
      ),
    );
  }

  //预售权限弹窗
  _buildPresaleContent(GlobalStore _, bool enough) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 30),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Color(0xff141414),
            Colors.black,
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          32.sizeBoxH,
          Text(
            '温馨提示',
            style: TextStyle(
              fontSize: 20,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
          18.sizeBoxH,
          Container(
            height: 0.5,
            color: Colors.black.withOpacity(0.1),
          ),
          18.sizeBoxH,
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 35),
            child: Text(
              presaleProvider.isNeedShowTime ? '当前免费观影次数已用完!\n支付尾款 享受完整超级会员特权' : '开通限时预售 全站视频免费观看\n查看更多会员特权',
              style: TextStyle(
                fontSize: 14,
                color: Colors.white,
                height: 2.0,
                fontWeight: FontWeight.w400,
              ),
              textAlign: TextAlign.center,
            ),
          ),
          24.sizeBoxH,
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 18),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Container(
                  height: 38,
                  width: 100,
                  child: InkWell(
                    onTap: () {
                      if (enough) {
                        _buyProduct(enough); //去支付
                      } else {
                        Get.to(MineChargeCoinPage());
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(.1),
                        borderRadius: BorderRadius.circular(22),
                      ),
                      child: Text(
                        '$mediaCoin金币支付',
                        style: const TextStyle(
                          fontSize: 14,
                          color: Colors.white,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  ),
                ),
                Container(
                  height: 38,
                  width: 130,
                  child: InkWell(
                    onTap: () => Get.to(() => PreSalePage()),
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Color(0xff3E64EA),
                        borderRadius: BorderRadius.circular(22),
                      ),
                      child: Text(
                        '前往活动',
                        style: const TextStyle(
                          fontSize: 14,
                          color: Colors.white,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          presaleProvider.benefitsTips(),
          18.sizeBoxH,
        ],
      ),
    );
  }

  Widget _buildNormal(bool enough) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 18),
      decoration: BoxDecoration(
        color: Color(0xff030F18),
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 36,
            height: 5,
            child: DecoratedBox(
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(.2),
                borderRadius: BorderRadius.circular(3),
              ),
            ),
          ),
          18.sizeBoxH,
          Text(
            '购买作品',
            style: TextStyle(
              color: Color(0xE5ffffff),
              fontSize: 20,
              fontWeight: FontWeight.w500,
            ),
          ),
          36.sizeBoxH,
          Row(
            children: [
              Text(
                '作品解锁',
                style: TextStyle(
                  color: Color(0xE5ffffff),
                  fontSize: 14,
                ),
              ),
              Spacer(),
              GestureDetector(
                onTap: () => jumpToWalletPage(tabPosition: 1),
                child: Row(
                  children: [
                    Image.asset(
                      'coin_x.webp'.commonImgPath,
                      width: 24,
                      height: 24,
                    ),
                    10.sizeBoxW,
                    Text(
                      '${widget.videoModel?.coins ?? 0} 金币',
                      style: TextStyle(
                        color: Color(0xffFF9000),
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
          18.sizeBoxH,
          // Row(
          //   children: [
          //     Text(
          //       '作品原价',
          //       style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w400),
          //     ),
          //     Spacer(),
          //     Text(
          //       '${widget.videoM.originCoins ?? 0} 金币',
          //       style: TextStyle(
          //         color: Color(0xffe0e0e0),
          //         fontSize: 14,
          //         decoration: (store.meInfo == null || store.meInfo?.vipLevel == 0) ? null : TextDecoration.lineThrough,
          //         decorationColor: Colors.white,
          //       ),
          //     ),
          //   ],
          // ),
          // 18.sizeBoxH,
          // Row(
          //   children: [
          //     Text(
          //           () {
          //         if (store.meInfo == null || store.meInfo?.vipLevel == 0) return '您当前不享受折扣优惠';
          //         final discount = ((widget.videoM.coins ?? 0) / (widget.videoM.originCoins ?? 0) * 10).toInt();
          //         if (discount == 10) return '您当前不享受会员折扣';
          //
          //         return '您当前享受$discount折优惠';
          //       }(),
          //       style: TextStyle(color: Color(0xffE2AA76), fontSize: 14, fontWeight: FontWeight.w400),
          //     ),
          //     Spacer(),
          //     GestureDetector(
          //       onTap: () => jumpToWalletPage(),
          //       child: Text(
          //             () {
          //           if (store.meInfo == null || store.meInfo?.vipLevel == 0) return '购买VIP享受折扣';
          //           // final discount = ((widget.videoM.coins ?? 0) / (widget.videoM.originCoins ?? 0) * 10).toInt();
          //           return '升级会员';
          //         }(),
          //         style: TextStyle(
          //           color: Color(0xffE2AA76),
          //           fontSize: 14,
          //           fontWeight: FontWeight.w400,
          //           decoration: TextDecoration.underline,
          //           decorationColor: Color(0xffE2AA76),
          //         ),
          //       ),
          //     ),
          //   ],
          // ),
          // 18.sizeBoxH,
          Divider(
            height: 0.5,
            color: Colors.white.withOpacity(.05),
          ),
          18.sizeBoxH,
          Row(
            children: [
              Text(
                '我的金币',
                style: TextStyle(
                  color: Color(0xE5ffffff),
                  fontSize: 14,
                ),
              ),
              Spacer(),
              Row(
                children: [
                  Text(
                    '${GlobalStore().wallet?.amount?.toDouble().fixed(2) ?? 0}',
                    style: TextStyle(
                      color: Color(0xE5ffffff),
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  12.sizeBoxW,
                  InkWell(
                    onTap: () => jumpToWalletPage(tabPosition: 1),
                    child: Text(
                      '充值',
                      style: TextStyle(
                          color: Color(0xffA4634D),
                          fontSize: 14,
                          fontWeight: FontWeight.w400,
                          decoration: TextDecoration.underline,
                          decorationColor: Color(0xffA4634D)),
                    ),
                  ),
                ],
              ),
            ],
          ),
          18.sizeBoxH,
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () => _buyProduct(enough),
            child: Container(
              width: double.infinity,
              height: 47,
              decoration: BoxDecoration(color: Color(0xffE1351F), borderRadius: BorderRadius.circular(3)),
              alignment: Alignment.center,
              child: Text(
                enough ? '${widget.videoModel?.coins ?? 0}金币/立即支付' : '余额不足，前往充值',
                style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
